package com.example.ss_shiro.controller;

import com.example.ss_shiro.entity.Account;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@Controller
public class AccountController {
    /**
     * 页面之间重定向
     * @param url
     * @return
     */
    @GetMapping("/{url}")
    public String redirect(@PathVariable("url") String url){
    return url;
    }

    /**
     * 登录逻辑编写
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public String login(String username,String password, Model model){
        //通过静态方法拿到subject ,里面是用户的信息,暂时还没有,与shiro对接的方法就是通过subject
        Subject subject= SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        //通过login 将token 放进subject 里面 ,自动进入定义的realm中
        try {
            subject.login(token);
            Account account =(Account) subject.getPrincipal();
            //将用户信息存入session;
            subject.getSession().setAttribute("account",account);
            return "index";
        } catch (UnknownAccountException e) {//realm 里面return null
            e.printStackTrace();
            model.addAttribute("msg","用户名错误!");
            return "login";
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            model.addAttribute("msg","密码错误!");
            return "login";
        }

    }

    /**
     * 未授权跳转页面
     * @return
     */
    @GetMapping("/unauth")
    @ResponseBody //此注解不加的话，前端是无法解析 java对象的
    public  String  unauth(){
        return "未授权,无法访问";
    }

    /**
     * 退出返回login页面
     * @return
     */
    @GetMapping("/logout")
    public  String  logout(){
        //取消当前session;清空
        Subject subject=SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
}
